package com.ten.java.doinit.service;

import com.ten.java.doinit.common.Context;
import com.ten.java.doinit.util.StringUtils;
import lombok.Data;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 数据库服务类
 * @author zhangxs
 * @date 2022/7/8 13:56
 */
public class DBService {

    /**
     * 创建JdbcTemplate
     * @param
     * @return JdbcTemplate
     * @author zhangxs
     * @date 2022/7/11 15:36
     */
    private static JdbcTemplate createJdbcTemlate() {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName(Context.Config.DRIVER_CLASS_NAME);
        dataSource.setUrl(Context.Config.url);
        dataSource.setUsername(Context.Config.username);
        dataSource.setPassword(Context.Config.password);
        return new JdbcTemplate(dataSource);
    }

    /**
     * 获取库中所有字段的信息
     * @param
     * @return Map<String,List<Column>>
     * @author zhangxs
     * @date 2022/7/11 15:37
     */
    public static Map<String, List<Column>> getTableInfo() {
        final JdbcTemplate jdbcTemlate = createJdbcTemlate();
        String sql = StringUtils.format("SELECT table_name, column_name, data_type, column_key, column_comment FROM information_schema.`COLUMNS` WHERE table_schema = '<>'", Context.Config.databaseName);
        List<Column> columns = jdbcTemlate.query(sql, new BeanPropertyRowMapper<>(Column.class));
        if (CollectionUtils.isEmpty(columns)) {
            return null;
        }
        return columns.stream().collect(Collectors.groupingBy(column -> column.getTableName()));
    }

    /**
     * 字段信息类
     * @author zhangxs
     * @date 2022/7/8 14:00
     */
    @Data
    public static class Column {

        // 表名
        private String tableName;

        // 字段名称
        private String columnName;

        // 字段类型
        private String dataType;

        // 字段索引
        private String columnKey;

        // 字段备注
        private String columnComment;
    }
}
